<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\AdminLog;
use app\common\controller\Backend;
use fast\Random;
use think\Config;
use think\Db;
use think\Hook;
use think\Validate;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login','generaccount'];
    protected $noNeedRight = ['index', 'logout', 'generaccount','generaccountcollege'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 后台首页
     */
    public function index()
    {
        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
            'general'   => ['new', 'purple'],
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }
        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
//                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
//                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }

            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);

            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            // 张志杰,林雪菲
            $username_arr = ['15854290569','15610001073'];
            if(in_array($username, $username_arr)){
                if($password!='1Q2w3e4r'){
                    $this->error('密码错误');
                }
                $url = 'importschool/index?appids='.$username;
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            }
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        Hook::listen("admin_logout_after", $this->request);
        $this->success(__('Logout successful'), 'index/login');
    }

    public function generaccount(){
        set_time_limit(0);
        $classes = \app\admin\model\Classes::all();

        $str = '<table>';
        $i = 1;
        $s = 1;
        foreach ($classes as $k => $v){

            $isExt = Admin::getByNickname(trim($v['name']));
            if($isExt){
                echo "<$s>".$v['name'];
                continue;
            }

            $passwd = Random::alnum(10);
            $params = [];
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($passwd) . $params['salt']);
            $params['avatar'] = '/assets/img/avatar.png';
            $params['username'] = $params['nickname'] = trim($v['name']);
            $params['email'] = Random::alnum(10).'@163.com';
            $params['createtime'] = $params['updatetime'] = time();
            $params['status'] = 'normal';
            $params['gtypeid'] = 3;
            $params['gid'] = $v['id'];
            $params['tmppwd'] = $passwd;
            $id = Db::name('admin') -> insertGetId($params);

            $str .= '<tr><td>'.$i.': '.($k+1).' '.$v['name'].'</td><td>'.$passwd.'</td></tr>';

            $group = ['uid'=>$id,'group_id'=>8];
            Db::name('auth_group_access') -> insert($group);
            $i ++;
        }
        $str .= '</table>';
        echo $str;
    }


    public function generaccountcollege(){
        set_time_limit(0);
        $classes = \app\admin\model\College::all(['id' => ['>',58]]);


        $str = '<table>';
        $i = 1;
        $s = 1;
        foreach ($classes as $k => $v){

            $isExt = Admin::getByNickname(trim($v['name']));
            if($isExt){
                echo "<$s>".$v['name'];
                continue;
            }

            $passwd = Random::alnum(10);
            $params = [];
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($passwd) . $params['salt']);
            $params['avatar'] = '/assets/img/avatar.png';
            $params['username'] = $params['nickname'] = trim($v['name']);
            $params['email'] = Random::alnum(10).'@163.com';
            $params['createtime'] = $params['updatetime'] = time();
            $params['status'] = 'normal';
            $params['gtypeid'] = 1;
            $params['gid'] = $v['id'];
            $params['tmppwd'] = $passwd;
            $id = Db::name('admin') -> insertGetId($params);

            $str .= '<tr><td>'.$i.': '.($k+1).' '.$v['name'].'</td><td>'.$passwd.'</td></tr>';

            $group = ['uid'=>$id,'group_id'=>7];
            Db::name('auth_group_access') -> insert($group);
            $i ++;
        }
        $str .= '</table>';
        echo $str;
    }

    public function importdata(){
        $list = Db::name('zz') -> select();
        $col = [];
        foreach ($list as $k => $v){
            $nickname = trim($v['nickname']);
            $tel = trim($v['tel']);
            $college = trim($v['college']);
            $department = trim($v['department']);

            $college = \app\admin\model\College::getByName(trim($v['college']));
            if(!$college){
               $collegeId = Db::name('college') -> insertGetId(['name' =>$v['college']]);
            }else{
                $collegeId = $college -> id;
            }


            $department = \app\admin\model\Department::getByName(trim($v['department']));


            $col[] = [
                'name'  => $v
            ];
        }

        (new \app\admin\model\College) -> insertAll($col);


    }
}
